<?php

namespace frontend\modules\business\controllers;

use common\components\Category;
use common\components\Helper;
use common\components\Upload;
use common\models\articlesite\ArticlesiteArticle;
use common\models\articlesite\ArticlesiteCategory;
use common\models\business\BusinessAdress;
use common\models\business\BusinessContract;
use common\models\business\BusinessCost;
use common\models\business\BusinessCostType;
use common\models\business\BusinessDisease;
use common\models\business\BusinessDiseaseType;
use common\models\business\BusinessException;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessGrowup;
use common\models\business\BusinessInspection;
use common\models\business\BusinessPerson;
use common\models\business\BusinessPig;
use common\models\business\BusinessPigFile;
use common\models\business\BusinessPigPrice;
use common\models\business\BusinessPut;
use common\models\business\BusinessPutDetail;
use common\models\business\BusinessUser;
use common\models\business\BusinessVaccine;
use common\models\business\BusinessVaccineSet;
use common\models\business\BusinessVariety;
use common\models\business\NewBusinessInspection;
use common\models\business\NewBusinessInspectionData;
use common\models\business\NewBusinessInspectionField;
use common\models\farmerhouse\FarmerhouseHouse;
use common\models\sys\SysSetting;
use frontend\controllers\BaseMobileController;
use maxwen\easywechat\Wechat;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Response;
use yii\web\YiiAsset;

/**
 * Class PersonController
 * @package frontend\modules\business\controllers
 * 业务人员相关控制器
 */
class PersonController extends BaseMobileController
{


    public $enableCsrfValidation = false;

    /**
     * @var array
     * 个人中心菜单
     */
    public static $menus = [
    ];

    public function beforeAction($action)
    {
        //判断是否是业务员，只有业务员可以访问此控制器
        $ise = \Yii::$app->db->createCommand('select id,name from '.BusinessPerson::tableName().' where openid=:openid and status=:status')
            ->bindValues([':openid'=>$this->user['openid'],':status'=>BusinessPerson::STATUS_JOB])
            ->queryOne();
        if(!$ise) {
            return $this->redirect('/business/user/index');
        }
        $this->user['personid'] = $ise['id'];
        $this->user['personname'] = $ise['name'];

        return parent::beforeAction($action);// TODO: Change the autogenerated stub
    }





    public function init()
    {
        self::$menus = [
            ['name' => '提醒说明','icon'=>"xiaoxi",'color'=>"mx_green",'link' => 'tip-explain'],
            ['name' => '仔猪分配','icon'=>"pencil",'color'=>"danger",'link' => 'fill-pig'],
            ['name' => '仔猪管理','icon'=>"menu",'color'=>"info",'link' => 'pig'],
            ['name' => '农户管理','icon'=>"user",'color'=>"mx_green",'link' => 'farmer'],
            ['name' => '联系后台','icon'=>"telephone",'color'=>"danger",'link' => 'tel:'.SysSetting::getValue('backendtel')],
        ];
        parent::init(); // TODO: Change the autogenerated stub
    }


    /**
     * @return array
     * 绑定页面
     */
    /*public function actionBind()
    {
        if(\Yii::$app->request->isPost)
        {
            $postdata = \Yii::$app->request->post();
            $person = BusinessPerson::find()->select('id')->where('num=:num and passwd=:passwd',[':num'=>$postdata['num'],':passwd'=>$postdata['passwd']])->asArray()->one();
            $res = false;
            if($person){
                $res = \Yii::$app->db->createCommand()->update(BusinessPerson::tableName(),['openid'=>$this->user['openid']],'id=:id',[':id'=>$person['id']]);
            }

            return $res?$this->jsonMsg():$this->jsonMsg('绑定失败',1);
        }

        $this->render('@template/mobile/businessbind.html',[
        ]);
    }*/





    /**
     * @return string
     * 个人中心
     */
    public function actionIndex()
    {
        return $this->render('@template/mobile/businessman_center.html',[
            'menus' => \GuzzleHttp\json_encode(self::$menus),
            'user' => $this->user
        ]);

    }


    /**
     * @return string
     * 个人资料
     */
    public function actionUserInfo()
    {

        $userinfo = BusinessPerson::find()->select('name,phone as tel,gender,descripation')->where('openid=:openid',[':openid'=>$this->user['openid']])->asArray()->one();


        return $this->render('@template/mobile/businessman_userinfo.html',[
            'userinfo'=>\GuzzleHttp\json_encode($userinfo),
            'isperson' => $this->user['personid'],
        ]);
    }


    public function actionPostUserinfo()
    {
        $postdata = \Yii::$app->request->post();
        $data = [
            'name' => $postdata['name'],
            'phone' => $postdata['tel'],
            'descripation' => $postdata['descripation'],
            'gender' => $postdata['gender'],
        ];
        $res = \Yii::$app->db->createCommand()->update(BusinessPerson::tableName(),$data,'id=:id',[':id'=>$this->user['personid']])->execute();
        $url = \yii\helpers\Url::to(['/business/person/index']);

        return $res?$this->jsonMsg('更新成功',0,['url' => $url]):$this->jsonMsg('网络问题',1);
    }


    /**
     * @return string
     * 农户管理
     */
    public function actionFarmer()
    {

        $subQuery = (new Query())->select('count(*)')->from(BusinessPig::tableName())->where('livery=f.id');

        $farmers = (new Query())->from(BusinessFarmers::tableName().' as f')
            ->select('f.id,f.name,f.addressdetail as address,p.name as owner,f.no,f.photo as img,f.status as stat,fh.id as house')
            ->leftJoin(BusinessPerson::tableName().' as p','p.id=f.introducer')
            ->leftJoin(FarmerhouseHouse::tableName().' as fh','fh.farmerid=f.id')
            ->addSelect(['status'=>$subQuery])
            ->where('f.introducer=:personid',[':personid'=>$this->user['personid']])
            ->all();

        foreach($farmers as $key => $row){
            $farmers[$key]['img'] = Upload::checkGetUrl($row['img']);
            $farmers[$key]['url'] = \yii\helpers\Url::to(['person/farmer-info','farmerid'=>$row['id']]);
            $farmers[$key]['houseurl'] = \yii\helpers\Url::to(['/business/person/farmer-request','farmerid'=>$row['id']]);
            $farmers[$key]['stat'] = BusinessFarmers::$statues[$row['stat']];
        }

        return $this->render('@template/mobile/businessman_farmers_manage.html',[
            'farmers'=>\GuzzleHttp\json_encode($farmers)
        ]);
    }



    //农户资料维护
    public function actionFarmerInfo()
    {
        $farmerid = \Yii::$app->request->get('farmerid');
        $address = BusinessAdress::find()->select('id,parentid,lat,lng,name')->where('status=:status',[':status'=>BusinessAdress::STATUS_ACTIVE])->asArray()->all();
        $address = Category::getTree($address,9);
        $farmer = [];
        if($farmerid){
            $farmer = (new Query())->from(BusinessFarmers::tableName().' as f')
                ->select('f.id as farmerid,f.no,f.name,,f.address,f.descripation,p.name as personname,pighousephoto as houseimg,identity_photo as infoimg,photo as personalimg,p.phone,f.identity,f.descripation,f.pighousedesc,f.countyid as province,f.townid as city,villageid as area')
                ->leftJoin(BusinessPerson::tableName().' as p','f.introducer=p.id')
                ->where('f.id=:id',[':id'=>$farmerid])
                ->one();

                $farmer['houseimg'] = Upload::checkGetUrl($farmer['houseimg'],true,'houseimg',false);
                $farmer['infoimg'] = Upload::checkGetUrl($farmer['infoimg'],true,'infoimg',false);
                $farmer['personalimg'] = Upload::checkGetUrl($farmer['personalimg'],true,'personalimg',false);

        }



        return $this->render('@template/mobile/businessman_farmers_detail_add.html',[
            'farmer'=>\GuzzleHttp\json_encode($farmer),
            'address' => \GuzzleHttp\json_encode($address),
            'farmerid' => $farmerid
        ]);
    }



    public function actionFarmerInfoAdd()
    {
        $address = BusinessAdress::find()->select('id,parentid,lat,lng,name')->where('status=:status',[':status'=>BusinessAdress::STATUS_ACTIVE])->asArray()->all();
        $address = Category::getTree($address,9);
//        var_dump(\GuzzleHttp\json_encode($address));exit;

        return $this->render('@template/mobile/businessman_farmers_detail_add.html',[
            'address' => \GuzzleHttp\json_encode($address)
        ]);
    }


    /**
     * @return array
     * 提交农户资料
     */
    public function actionPostFarmerInfo()
    {
        $postdata = \Yii::$app->request->post();


        $province = BusinessAdress::findOne($postdata['province']);
        $city = BusinessAdress::findOne($postdata['city']);
        $area = BusinessAdress::findOne($postdata['area']);

        //取出编号
        $no = BusinessFarmers::find()->max('id');
        $data = [
            'countyid' => $postdata['province'],
            'townid' => $postdata['city'],
            'villageid' => $postdata['area'],
            'address' => $postdata['address'],
            'phone' => $postdata['phone'],
            'name' => $postdata['name'],
            'gender' => $postdata['gender'],
            'identity' => $postdata['identity'],
            'descripation' => $postdata['descripation'],
            'pighousedesc' => $postdata['pighousedesc'],
            'addressdetail' => $province->name.$city->name.$area->name.$postdata['address'],
            'status' => BusinessFarmers::STATUS_HAGREE,
            'no' => str_pad($no+1,8,"0",STR_PAD_LEFT),
        ];


        $farmer = BusinessFarmers::find()->select('identity_photo,pighousephoto,photo')->where('id=:fid',[':fid'=>$postdata['farmerid']])->asArray()->one();

        //处理图片
        if($postdata['infoimg']){
            $infoimgs = Upload::uploadBase64($postdata['infoimg']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($farmer['identity_photo'])){
                $infoimgs = $farmer['identity_photo'].'|'.$infoimgs;
            }
            $data['identity_photo'] = $infoimgs;
        }
        if($postdata['houseimg']){
            $infoimgs = Upload::uploadBase64($postdata['houseimg']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($farmer['pighousephoto'])){
                $infoimgs = $farmer['pighousephoto'].'|'.$infoimgs;
            }
            $data['pighousephoto'] = $infoimgs;
        }
        if($postdata['photo']){
            $infoimgs = Upload::uploadBase64($postdata['photo']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($farmer['photo'])){
                $infoimgs = $farmer['photo'].'|'.$infoimgs;
            }
            $data['photo'] = $infoimgs;
        }

        //入库
        if($postdata['farmerid']){
            $res = \Yii::$app->db->createCommand()->update(BusinessFarmers::tableName(),$data,'id=:farmerid',[':farmerid'=>$postdata['farmerid']])->execute();
        }else{
            $data['introducer'] = $this->user['personid'];
            $res = \Yii::$app->db->createCommand()->insert(BusinessFarmers::tableName(),$data)->execute();
        }
        if($res!==false){
            return $this->jsonMsg();
        }else{
            return $this->jsonMsg('修改失败',1);
        }

    }


    /**
     * @return array
     * 删除农户的图片
     */
    public function actionDeleteFarmerImg()
    {
        $postdata = \Yii::$app->request->post();
        $type = $postdata['type'];
        $offect = $postdata['key'];
        $farmer = BusinessFarmers::find()
            ->select($type)
            ->where('id=:farmerid',[':farmerid'=>$postdata['farmerid']])
            ->asArray()
            ->one();
        if (strpos($farmer[$type],'|')){
            $imgs = explode('|',$farmer[$type]);
            foreach($imgs as $key => $row){
                if($key == $offect){
                    Upload::deleteImg($imgs[$key]);
//                    unlink(Upload::checkGetPath($imgs[$key]));
                    unset($imgs[$key]);
                }
            }
            $imgs = implode('|',$imgs);
        }else{
            $res = Upload::deleteImg($farmer[$type]);
            $imgs = '';
        }

        $res = \Yii::$app->db->createCommand()
            ->update(BusinessFarmers::tableName(),[$type=>$imgs],'id=:farmerid',[':farmerid'=>$postdata['farmerid']])
            ->execute();

        return $res!==false?$this->jsonMsg():$this->jsonMsg('删除失败',1);
    }



    /**
     * @return array
     * 删除农家乐的图片
     */
    public function actionDeleteHouseImg()
    {
        $postdata = \Yii::$app->request->post();
        $type = $postdata['type'];
        $offect = $postdata['key'];
        $farmer = FarmerhouseHouse::find()
            ->select($type)
            ->where('id=:id',[':id'=>$postdata['id']])
            ->asArray()
            ->one();
        if (strpos($farmer[$type],'|')){
            $imgs = explode('|',$farmer[$type]);
            foreach($imgs as $key => $row){
                if($key == $offect){
                    Upload::deleteImg($imgs[$key]);
//                    unlink(Upload::checkGetPath($imgs[$key]));
                    unset($imgs[$key]);
                }
            }
            $imgs = implode('|',$imgs);
        }else{
            $res = Upload::deleteImg($farmer[$type]);
            $imgs = '';
        }

        $res = \Yii::$app->db->createCommand()
            ->update(FarmerhouseHouse::tableName(),[$type=>$imgs],'id=:id',[':id'=>$postdata['id']])
            ->execute();

        return $res!==false?$this->jsonMsg():$this->jsonMsg('删除失败',1);
    }








    /**
     * @param $farmerid
     * @return string
     * 农家乐
     */
    public function actionFarmerRequest($farmerid)
    {
        $address = BusinessAdress::find()->select('id,parentid,lat,lng,name')->where('status=0')->asArray()->all();
        $address = Category::getTree($address,9);

        $farmer = (new Query())->from(BusinessFarmers::tableName().' as f')
            ->select('f.no,f.name,,f.address,f.descripation,p.name as personname,p.phone')
            ->leftJoin(BusinessPerson::tableName().' as p','f.introducer=p.id')
            ->where('f.id=:id',[':id'=>$farmerid])
            ->one();

        $house = FarmerhouseHouse::find()
            ->select('*')
            ->where('farmerid=:fid',[':fid'=>$farmerid])
            ->asArray()
            ->one();
        if($house){
            $house['envphoto'] = Upload::checkGetUrl($house['envphoto'],true,'envphoto',false);
            $house['accommodationphoto'] = Upload::checkGetUrl($house['accommodationphoto'],true,'accommodationphoto',false);
        }
        return $this->render('@template/mobile/businessman_farmers_request.html',[
//            'farmer'=>\GuzzleHttp\json_encode($farmer),
            'farmer'=>$farmer,
            'house' => $house,
            'jsonhouse' => \GuzzleHttp\json_encode($house),
        ]);
    }


    /**
     * @return array
     * 提交农家乐数据
     */
    public function actionPostFarmerRequest()
    {
        $postdata = \Yii::$app->request->post();

        $farmer = BusinessFarmers::find()
            ->select('countyid,townid,villageid,address')
            ->where('id=:id',[':id'=>$postdata['farmerid']])
            ->asArray()
            ->one();
        $house = FarmerhouseHouse::find()
            ->select('envphoto,accommodationphoto')
            ->where('farmerid=:fid',[':fid'=>$postdata['farmerid']])
            ->asArray()
            ->one();

        $data = [
            'name' => $postdata['name'],
            'status' => FarmerhouseHouse::STATUS_NOLOOK,
            'farmerid' => $postdata['farmerid'],
            'roomnum' => $postdata['number'],
            'caninnum' => $postdata['max_num'],
            'personid' => $this->user['personid'],
            'price' => $postdata['price'],
            'canfeed' => $postdata['canfeed'],
            'envdesc' => $postdata['envdesc'],
            'accommodation' => $postdata['accommodation'],
            'county' => $farmer['countyid'],
            'town' => $farmer['townid'],
            'village' => $farmer['villageid'],
            'address' => $farmer['address'],
            'createtime' => time(),
        ];


        if($postdata['envphoto']){
            $infoimgs = Upload::uploadBase64($postdata['envphoto']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($house['envphoto'])){
                $infoimgs = $house['envphoto'].'|'.$infoimgs;
            }
            $data['envphoto'] = $infoimgs;
        }
        if($postdata['accommodationphoto']){
            $infoimgs = Upload::uploadBase64($postdata['accommodationphoto']);
            $infoimgs = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            if(!empty($house['accommodationphoto'])){
                $infoimgs = $house['accommodationphoto'].'|'.$infoimgs;
            }
            $data['accommodationphoto'] = $infoimgs;
        }


        $ise =  FarmerhouseHouse::findOne(['farmerid'=>$postdata['farmerid']]);
        if($ise == null){
            $res = \Yii::$app->db->createCommand()->insert(FarmerhouseHouse::tableName(),$data)->execute();
        }else{
            $res = \Yii::$app->db->createCommand()->update(FarmerhouseHouse::tableName(),$data,'farmerid=:fid',[':fid'=>$postdata['farmerid']])->execute();
        }
        return $res?$this->jsonMsg():$this->jsonMsg('失败',1);

    }




    /**
     * @return string
     * 仔猪管理
     */
    public function actionPig()
    {

        $cates = BusinessVariety::find()->select('id,title as name')->asArray()->all();
        foreach ($cates as $key => $row){
            $cates[$key]['url'] = Url::to(['/business/person/pig','cateid'=>$row['id']]);
        }
        $cateid = \Yii::$app->request->get('cateid');

        $query = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.id,p.status,p.no,p.headperson as owner,p.liveryname as farmer,p.photo as img,v.title as type')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id');

        if($cateid){
            $query = $query->where('p.headpersonid=:id and p.varietyid=:cateid and livery!=0',[':id'=>$this->user['personid'],':cateid'=>$cateid]);
        }else{
            $query = $query->where('p.headpersonid=:id and livery!=0',[':id'=>$this->user['personid']]);
        }

        $pigesize  = 100;
        $pindex = \Yii::$app->request->post('pindex');
        $pindex = $pindex?$pindex:1;
        if(\Yii::$app->request->isPost){
            $pigs = $query->limit($pigesize)->offset($pindex*$pigesize)
                ->all();
            \Yii::$app->response->format = Response::FORMAT_JSON;
//            foreach ($pigs as $key => $value){
//                if(BusinessPig::newIsInspection($value['id'])){
//                    $pigs[$key]['disorder'] = $key;
//                }else{
//                    $pigs[$key]['disorder'] = 0;
//                }
//                $pigs[$key]['img'] = Upload::checkGetUrl($value['img']);
//                $pigs[$key]['oldstatus'] = $value['status'];
//                $pigs[$key]['status'] = BusinessPig::$statues[$value['status']];
//                $pigs[$key]['url'] = \yii\helpers\Url::to(['person/pig-detail','pigid'=>$value['id']]);
//            }

            foreach ($pigs as $key => $value){
                //在巡检周期内是否巡检  巡检的放在后面，按照disorder升序排序
                $isspec = BusinessPig::newIsInspection($value['id']);
                if(!empty($isspec)){
                    if($isspec['insstatus'] == NewBusinessInspection::STATUS_PASSED){
                        $pigs[$key]['disorder'] = 3;
                        $pigs[$key]['insmstatus'] = '已审核';
                    }else if($isspec['insstatus'] == NewBusinessInspection::STATUS_UNPASSED){
                        $pigs[$key]['disorder'] = 1;
                        $pigs[$key]['insmstatus'] = '未通过';
                    }else if($isspec['insstatus'] == NewBusinessInspection::STATUS_NOLOOK){
                        $pigs[$key]['disorder'] = 2;
                        $pigs[$key]['insmstatus'] = '待审核';
                    }
                    $pigs[$key]['insstatus'] = $isspec['insstatus'];
                }else{
                    $pigs[$key]['disorder'] = 0;
                    $pigs[$key]['insmstatus'] = '待审核';
                }
                $pigs[$key]['img'] = Upload::checkGetUrl($value['img']);
                $pigs[$key]['oldstatus'] = $value['status'];
                $pigs[$key]['status'] = BusinessPig::$statues[$value['status']];
                $pigs[$key]['url'] = \yii\helpers\Url::to(['person/pig-detail','pigid'=>$value['id']]);
            }
            ArrayHelper::multisort($pigs, ['disorder'], [SORT_DESC]);
            return $pigs;

        }else{
            $pigs = $query->limit($pigesize)
                ->all();
        }

        foreach ($pigs as $key => $value){
            //在巡检周期内是否巡检  巡检的放在后面，按照disorder升序排序
            $isspec = BusinessPig::newIsInspection($value['id']);
            if(!empty($isspec)){
                if($isspec['insstatus'] == NewBusinessInspection::STATUS_PASSED){
                    $pigs[$key]['disorder'] = 3;
                    $pigs[$key]['insmstatus'] = '已审核';
                }else if($isspec['insstatus'] == NewBusinessInspection::STATUS_UNPASSED){
                    $pigs[$key]['disorder'] = 1;
                    $pigs[$key]['insmstatus'] = '未通过';
                    //取出未通过的原因
                    $pigs[$key]['statusremark'] = $isspec['remark'];
                    $pigs[$key]['insid'] = $isspec['id'];
                }else if($isspec['insstatus'] == NewBusinessInspection::STATUS_NOLOOK){
                    $pigs[$key]['disorder'] = 2;
                    $pigs[$key]['insmstatus'] = '待审核';
                }
                $pigs[$key]['insstatus'] = $isspec['insstatus'];
            }else{
                $pigs[$key]['disorder'] = 0;
                $pigs[$key]['insmstatus'] = '待审核';
            }
            $pigs[$key]['img'] = Upload::checkGetUrl($value['img']);
            $pigs[$key]['oldstatus'] = $value['status'];
            $pigs[$key]['status'] = BusinessPig::$statues[$value['status']];
            $pigs[$key]['url'] = \yii\helpers\Url::to(['person/pig-detail','pigid'=>$value['id']]);
        }

        ArrayHelper::multisort($pigs, 'disorder', SORT_ASC);
        return $this->render('@template/mobile/businessman_pigs_manage.html',[
            'lists' => \GuzzleHttp\json_encode($pigs),
            'cates' => $cates,
            'navs' => \GuzzleHttp\json_encode($cates)
        ]);
    }


    /**
     * @param $pigid
     * @return string
     * 仔猪详情
     */
    public function actionPigDetail($pigid)
    {
        //取出仔猪信息
        $pig = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.id,p.status,p.batch,p.no,p.photo,p.batch,p.intime,p.headperson as owner,liveryname as operator,p.killplace as slaughterhouse,v.title as type,f.address,pf.father as f_no,pf.mathor as m_no,c.partyA,c.no as contract_no')
            ->addSelect('pf.matherphoto as m_img,fatherphoto as f_img,f.pighousephoto')
            ->leftJoin(BusinessFarmers::tableName().' as f','p.livery=f.id')
            ->leftJoin(BusinessVariety::tableName().' as v','v.id=p.varietyid')
            ->leftJoin(BusinessPigFile::tableName().' as pf','pf.id=p.fileid')
            ->leftJoin(BusinessContract::tableName().' as c','c.id=pf.constract_id')
            ->where('p.id=:id',[':id'=>$pigid])
            ->one();
        if(!$pig){
            return $this->timealert('对应的仔猪不存在');
        }

        //处理数据
        $pig['oldstatus'] = $pig['status'];
        $pig['status'] = BusinessPig::$statues[$pig['status']];
        $pig['m_img'] = Upload::checkGetUrl($pig['m_img']);
        $pig['f_img'] = Upload::checkGetUrl($pig['f_img']);
        $pig['surroundings'] = Upload::checkGetUrl($pig['pighousephoto'],true);
        $pig['period'] = date('Y-m-d',$pig['intime']);

        //取出巡检记录
//        $records = BusinessInspection::find()->select('id,createtime,business_person')->where('pigid=:pigid and status=:status and is_del=:is_del',[':pigid'=>$pigid,':status'=>BusinessInspection::STATUS_PASSED,':is_del'=>BusinessInspection::ISDEL_NODEL])->asArray()->all();
        $records = NewBusinessInspection::find()->select('id,createtime,business_person')->where('pigid=:pigid and status=:status and is_del=:is_del',[':pigid'=>$pigid,':status'=>BusinessInspection::STATUS_PASSED,':is_del'=>BusinessInspection::ISDEL_NODEL])->asArray()->all();
        foreach ($records as $key => $row)
        {
            $records[$key]['title'] = date('Y-m-d',$row['createtime']);
            $records[$key]['no'] = $key+1;
            $records[$key]['who'] = $row['business_person'];
            $records[$key]['url'] = \yii\helpers\Url::to(['person/new-inspection-detail','id'=>$row['id']]);
        }
        $pig['records'] = $records;


        //取出疫苗
        $vaccine = BusinessVaccine::find()->select("id,remark,date as createtime")->where('pigid=:pigid',[':pigid'=>$pigid])->asArray()->all();
        foreach ($vaccine as $key => $value){
            $vaccine[$key]['createtime'] = date('Y-m-d',$value['createtime']);
        }
        $pig['vaccine'] = $vaccine;

        //取出成本
        $costs = BusinessCost::find()
            ->select('type as title,price,description as content')
            ->where('pigid=:pigid',[':pigid'=>$pigid])
            ->asArray()
            ->all();
        $pig['costs'] = $costs;
        $pig['totalcost'] = array_sum(ArrayHelper::getColumn($costs,'price'));


        //取出banner
        $banner = Upload::checkGetUrl($pig['photo'],true);
        return $this->render('@template/mobile/businessman_pigs_detail.html',[
            'detail' => \GuzzleHttp\json_encode($pig),
            'pigid' => $pigid,
            'banner' => $banner
        ]);
    }

    /**
     * @return array
     * 添加疫苗
     */
    public function actionPostVaccine()
    {
        $postdata = \Yii::$app->request->post();


        $vaccinename = (new Query())->select('vaccinename')
            ->from(BusinessVaccineSet::tableName())
            ->where('id=:id',[':id'=>$postdata['vaccineid']])
            ->scalar();
        $data = [
//            'date' => strtotime($postdata['createtime']),     //经过二次需求更改后去掉了
            'pigid' => $postdata['pigid'],
            'remark' => $postdata['remark'],
            'createtime' => time(),
            'date' => strtotime(date('Y-m-d')),
            'vaccineid' => $postdata['vaccineid'],
            'vaccinename' => $vaccinename,
        ];

        $res = \Yii::$app->db->createCommand()->insert(BusinessVaccine::tableName(),$data)->execute();

        //取出仔猪所属批次
        $price = (new  Query())->select('price')->from(BusinessVaccineSet::tableName())->where('id=:vaccineid',[':vaccineid'=>$postdata['vaccineid']])
            ->scalar();

        //取出疫苗成本
        //自动添加一项成本
        $costdata = [
            'pigid' => $postdata['pigid'],
            'type' => '疫苗',
            'personid' => $this->user['personid'],
            'person' => $this->user['personname'],
            'price' => $price,
            'description' => $postdata['remark'],
            'createtime' => time()
        ];
        $res = \Yii::$app->db->createCommand()->insert(BusinessCost::tableName(),$costdata)->execute();

        return $res?$this->jsonMsg():$this->jsonMsg('添加失败',1);
    }



    /**
     * @return string
     * 仔猪代养
     */
    public function actionFillPig()
    {
        $cates = BusinessVariety::find()->select('id,title as name')->asArray()->all();
        foreach ($cates as $key => $row){
            $cates[$key]['url'] = Url::to(['/business/person/pig','cateid'=>$row['id']]);
        }
        $cateid = \Yii::$app->request->get('cateid');
        $query = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.livery,p.id,p.no,headperson as owner,p.status,v.title as type,p.photo as img')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id');
        if($cateid){
            $pigs = $query->where('p.headpersonid=:id and varietyid=:cateid and livery=0',[':id'=>$this->user['personid'],':cateid'=>$cateid])
                ->all();
        }else{
            $pigs = $query->where('p.headpersonid=:id and livery=0',[':id'=>$this->user['personid']])
                ->all();
        }

        foreach($pigs as $key => $row){
            $pigs[$key]['status'] = BusinessPig::$statues[$row['status']];
            $pigs[$key]['img'] = Upload::checkGetUrl($row['img']);
            $pigs[$key]['url'] = \yii\helpers\Url::to(['person/fill-pig-farmer','pigid'=>$row['id']]);
        }

        return $this->render('@template/mobile/businessman_raising.html',[
            'lists' => \GuzzleHttp\json_encode($pigs),
            'cates' => $cates,
            'navs' => \GuzzleHttp\json_encode($cates)
        ]);
    }



    /**
     * @param $pigid
     * @return array|string
     * 分配仔猪给指定的农户(仔猪录入)
     */
    public function actionFillPigFarmer($pigid)
    {

        //取出业务员管理的农户
        $farmers = BusinessFarmers::find()->select('id,name')
            ->where('introducer=:id and status=:status',[':id'=>$this->user['personid'],':status'=>BusinessFarmers::STATUS_AGREE])
            ->asArray()->all();


        //取出仔猪信息
        $pig = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.livery,p.fileid,p.liveryremark,p.no,headperson as owner,v.title as type,p.batch as pici,photo as img')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id')
            ->where('p.id=:id',[':id'=>$pigid])
            ->one();

        $file = (new Query())->select('father as f_no,mathor as m_no')->from(BusinessPigFile::tableName())->where('id=:fid',[':fid'=>$pig['fileid']])->one();

        $pig['m_no'] = $file['m_no'];
        $pig['f_no'] = $file['f_no'];

        $pig['farmerlist'] = $farmers;
        $pig['img'] = Upload::checkGetUrl($pig['img']);
        return $this->render('@template/mobile/businessman_raising_detail.html',[
            'lists' => \GuzzleHttp\json_encode($pig),
            'pig' => $pig
        ]);

    }


    /**
     * @return array
     * 分配养猪人
     */
    public function actionPostFillPigFarmer()
    {
        $postdata = \Yii::$app->request->post();
        $farmer = BusinessFarmers::findOne(['id'=> $postdata['liveryid']]);
        $res = \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),[
            'livery' => $postdata['liveryid'],
            'liveryname' => $farmer->name,
            'liveryremark' => $postdata['liveryremark'],
            'status' => BusinessPig::STATUS_AFTERIN
        ],'id=:id',[':id'=>$postdata['pigid']])->execute();
        if($res){
            return $this->jsonMsg('分配成功',0);
        }else{
            return $this->jsonMsg('分配失败',1);
        }
    }


    /**
     * 常规巡检
     */
    public function actionPutInspection()
    {

        //取出当前的季节
        $thisdate = date('n');
        if($thisdate>=1 && $thisdate<=3){
            $default = '春节';
        }else if($thisdate>=4 && $thisdate<=6){
            $default = '夏季';
        }else if($thisdate>=7 && $thisdate<=9){
            $default = '秋季';
        }else{
            $default = '冬季';
        }

        $items = [
            ['name'=>"胸围",'field'=>'width',"ltype"=>'int','unit'=>'单位cm','type'=>'input'],
//            ['name'=>"身高","ltype"=>'int','unit'=>'单位cm','type'=>'input'],
            ['name'=>"体长",'field'=>'length',"ltype"=>'int','unit'=>'单位cm','type'=>'input'],
            ['name'=>"公式系数",'field'=>'xishu',"ltype"=>'int','unit'=>'','type'=>'select','data'=>['148','152','156']],
            ['name'=>"体重",'field'=>'weight',"ltype"=>'int','unit'=>'单位kg','type'=>'input'],
            ['name'=>"精神状态",'field'=>'activelevel',"ltype"=>'char','unit'=>'','type'=>'select','data'=>['','活跃','有活力','无力，倦怠']],
            ['name'=>'毛色','field'=>'haircolor',"ltype"=>'char','unit'=>'','type'=>'select','data'=>['黑色']],
            ['name'=>'饮食','field'=>'foodintake',"ltype"=>'char','unit'=>'','type'=>'select','data'=>['','正常','不正常']],
            ['name'=>'大便','field'=>'shit',"ltype"=>'char','unit'=>'','type'=>'select','data'=>['','松软成团','干硬如珠','色泽异常','有异味']],
            ['name'=>'体温整数','field'=>'temperature_shi',"ltype"=>'int','unit'=>'','type'=>'select','default'=>'','data'=>['',35,36,37,38,39,40,41]],
            ['name'=>'体温小数','field'=>'temperature_fen',"ltype"=>'int','unit'=>'','type'=>'select','default'=>'','data'=>['',1,2,3,4,5,6,7,8,9]],
            ['name'=>"呼吸<span style='font-size: 12px;color: red;'>(正常)</span>",'field'=>'breath',"ltype"=>'int','unit'=>'','type'=>'select','default'=>'','data'=>['',1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,27,30]],
            ['name'=>'消毒','field'=>'disinfection',"ltype"=>'int','unit'=>'单位次/周','type'=>'select','default'=>'','data'=>['',1,2,3,4,5,6,7]],
            ['name'=>'清圈','field'=>'cleanpen',"ltype"=>'int','unit'=>'单位次/周','type'=>'select','default'=>'','data'=>['',1,2,3,4,5,6,7]],
            ['name'=>'尿色','field'=>'urine',"ltype"=>'char','unit'=>'','type'=>'select','default'=>'','data'=>['','透明','浑浊','清亮']],
            ['name'=>'季节','field'=>'season',"ltype"=>'int','unit'=>'季节','type'=>'select','default'=>$default,'data'=>['春季','夏季','秋季','冬季']],
            ['name'=>'环境温度','field'=>'pen_temperature',"ltype"=>'int','unit'=>'摄氏度','type'=>'select','default'=>25,'data'=>[]],
        ];

        return $this->render('@template/mobile/businessman_inspection_input.html',[
            'healthy_status' => BusinessInspection::$healthys,
            'body_status' => BusinessInspection::$situation,
            'pigpen_status' => BusinessInspection::$pigpens,
            'items' => \GuzzleHttp\json_encode($items)
        ]);

    }


    /**
     * 常规巡检(优化将巡检字段做成活)
     */
    public function actionNewPutInspection()
    {

        $items = (new Query())->select('*')->from(NewBusinessInspectionField::tableName())->orderBy('displayorder desc')->all();
        $nitems = [];
        foreach ($items as $key => $row){
            if($row['type'] == NewBusinessInspectionField::TYPE_INPUT || $row['type'] == NewBusinessInspectionField::TYPE_SELECT){
                $row['data'] = explode(',',$row['data']);
                $nitems['input'][] = $row;
            }else if($row['type'] == NewBusinessInspectionField::TYPE_IMAGE){
                $nitems['image'][] = $row;
            }else if($row['type'] == NewBusinessInspectionField::TYPE_TEXTAREA){
                $nitems['textarea'][] = $row;
            }
        }
        unset($items);
        return $this->render('@template/mobile/new_businessman_inspection_input.html',[
            'healthy_status' => BusinessInspection::$healthys,
            'body_status' => BusinessInspection::$situation,
            'pigpen_status' => BusinessInspection::$pigpens,
            'items' => \GuzzleHttp\json_encode($nitems),
            'bujian' => \Yii::$app->request->get('bujian'),
            'insid' => \Yii::$app->request->get('insid'),
        ]);

    }


    /**
     * @return array
     * 提交常规巡检内容
     */
    public function actionNewPostInspection()
    {
        $postdata = \Yii::$app->request->post();

        $fields = NewBusinessInspectionField::allField();

        $ise = \Yii::$app->db->createCommand('select id from '.NewBusinessInspection::tableName().' where pigid=:id and FROM_UNIXTIME(createtime,"%Y-%m-%d")=:thisdate')
            ->bindValues([':id'=>$postdata['pigid'],':thisdate'=>date('Y-m-d')])
            ->queryScalar();
        if($ise && $postdata['bujian'] != 1){
            return $this->jsonMsg('今天已经巡检完成',0);
        }


        $insdata = [
            'pigid' => $postdata['pigid'],
            'business_person' => $this->user['personname'],
            'business_personid' => $this->user['personid'],
            'createtime' => time(),
            'lat' =>$postdata['lat'],
            'lng' => $postdata['lng'],
            'address' => $postdata['province'].$postdata['city'].$postdata['district'].$postdata['street'],
            'createtime' => time()
        ];

        //补检操作
        if($postdata['bujian'] == 1){
            $preinspec = (new Query())->select('createtime,id,bujian_id')
                ->from(NewBusinessInspection::tableName())
                ->where('id=:insid',[':insid'=>$postdata['insid']])
                ->one();

            //永远是第一个记录的补检
//            if(empty($preinspec['bujian_id'])){
//                $insdata['bujian_id'] = $postdata['insid'];
//            }else{
//                $insdata['bujian_id'] = $preinspec['bujian_id'];
//            }
            $insdata['bujian_id'] = $postdata['insid'];
            $insdata['type'] = NewBusinessInspection::TYPE_BUJIAN;
            $insdata['createtime'] = $preinspec['createtime'];
        }
        \Yii::$app->db->createCommand()->insert(NewBusinessInspection::tableName(),$insdata)->execute();
        $inspectionid = \Yii::$app->db->getLastInsertID();
        unset($insdata);

        $column = ArrayHelper::getColumn($fields,'name');
        foreach ($postdata as $key => $row){
            if(!in_array($key,$column)){
                continue;
            }
            $data = [
                'inspectionid' => $inspectionid,
                'fieldname' => $key,
                'fieldtype' => $fields[$key]['type'],
                'viewwidth' => $fields[$key]['viewwidth'],
                'isshow' => $fields[$key]['isshow'],
            ];
            //处理图片
            if($fields[$key]['type'] == 'image'){
                $imgs = Upload::uploadBase64($row);
                $photo = is_array($imgs)?implode('|',$imgs):$imgs;
                $data['val'] = $photo;
            }else{
                $data['val'] = $row.$fields[$key]['unit'];
            }
            $res = \Yii::$app->db->createCommand()->insert(NewBusinessInspectionData::tableName(),$data)->execute();
        }

        return $res?$this->jsonMsg('提交成功',0):$this->jsonMsg('提交失败',1);
    }

    /**
     * @return array
     * 提交常规巡检内容
     */
    public function actionPostInspection()
    {
        $postdata = \Yii::$app->request->post();

        $ise = \Yii::$app->db->createCommand('select id from '.BusinessInspection::tableName().' where pigid=:id and FROM_UNIXTIME(createtime,"%Y-%m-%d")=:thisdate')
            ->bindValues([':id'=>$postdata['pigid'],':thisdate'=>date('Y-m-d')])
            ->queryScalar();
        if($ise){
            return $this->jsonMsg('今天已经巡检完成',0);
        }
        $data = [
            'pigid' => $postdata['pigid'],
            'business_person' => $this->user['personname'],
            'business_personid' => $this->user['personid'],
            'healthy' => $postdata['healthy'],
            'healthy_desc' => $postdata['healthy_desc'],
            'width' => $postdata['width'],
//            'height' => $postdata['height'],          //后来沟通去掉
            'length' => $postdata['length'],
            'weight' => $postdata['weight'],
            'activelevel' => $postdata['activelevel'],
            'haircolor' => $postdata['haircolor'],
            'foodintake' => $postdata['foodintake'],
            'shit' => $postdata['shit'],
            'temperature' => floatval($postdata['temperature_shi'].'.'.$postdata['temperature_fen']),
            'breath' => $postdata['breath'],
            'cleanpen' => $postdata['cleanpen'],
            'season' => $postdata['season'],
            'disinfection' => $postdata['disinfection'],
            'urine' => $postdata['urine'],
            'pen_temperature' => $postdata['pen_temperature'],
            'pigpen' => $postdata['pigpen'],
            'pigpen_desc' => $postdata['pigpen_desc'],
            'createtime' => time(),
            'feed' => $postdata['foodssituation'],
            'feed_desc' => $postdata['foods_desc'],
            'situation' => $postdata['situation'],
            'lat' =>$postdata['lat'],
            'lng' => $postdata['lng'],
            'address' => $postdata['province'].$postdata['city'].$postdata['district'].$postdata['street']
        ];


        //处理图片
        if($postdata['pigimg']){
            $infoimgs = Upload::uploadBase64($postdata['pigimg']);
            $pigphoto = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            $data['pigphoto'] = $pigphoto;
        }
        if($postdata['penimg']){
            $infoimgs = Upload::uploadBase64($postdata['penimg']);
            $pigpen_photo = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            $data['pigpen_photo'] = $pigpen_photo;
        }
        if($postdata['foodsimg']){
            $infoimgs = Upload::uploadBase64($postdata['foodsimg']);
            $feed_photo = is_array($infoimgs)?implode('|',$infoimgs):$infoimgs;
            $data['feed_photo'] = $feed_photo;
        }

        $res = \Yii::$app->db->createCommand()->insert(BusinessInspection::tableName(),$data)->execute();

        return $res?$this->jsonMsg('提交成功',0):$this->jsonMsg('提交失败',1);
    }


    /**
     * @param $id
     * @return string
     * 巡检详情
     */
    public function actionInspectionDetail($id)
    {

        $detail = BusinessInspection::find()
            ->select('id,cleanpen,disinfection,urine,season,pen_temperature,healthy as health,healthy_desc as healthinfo,situation,feed,feed_desc,feed_photo as f_imgs,weight,height,length,width,pigpen as pighouse,pigpen_desc as pighouseinfo,pigpen_photo as p_imgs,pigphoto as s_imgs')
            ->addSelect('activelevel,haircolor,foodintake,shit,temperature,breath')
            ->where('id=:id',[':id'=>$id])
            ->asArray()
            ->one();
        $detail['s_imgs'] = Upload::checkGetUrl($detail['s_imgs'],true);
        $detail['p_imgs'] = Upload::checkGetUrl($detail['p_imgs'],true);
        $detail['f_imgs'] = Upload::checkGetUrl($detail['f_imgs'],true);

        $situationinfo = [
//            '身高' => $detail['height'].'cm',
            '胸围' => $detail['width'].'cm',
            '体长' => $detail['length'].'cm',
            '体重' => $detail['weight'].'kg',
            '精神状态' => $detail['activelevel'],
            '毛色' => $detail['haircolor'],
            '饮食' => $detail['foodintake'],
            '大便情况' => $detail['shit'],
            '体温' => $detail['temperature'].'℃',
            '呼吸' => $detail['breath'],
            '清圈' => $detail['cleanpen'].'次/周',
            '消毒' => $detail['disinfection'].'次/周',
            '尿色' => $detail['urine'],
            '季节' => $detail['season'],
            '环境温度' => $detail['pen_temperature'].'℃',
        ];

        $detail['situationinfo'] = $situationinfo;

        return $this->render('@template/mobile/businessman_inspection_detail.html',[
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);
    }

    /**
     * @param $id
     * @return string
     * 巡检详情
     */
    public function actionNewInspectionDetail($id)
    {

        $detail= (new Query())->select('*')->from(NewBusinessInspectionData::tableName())
            ->where('inspectionid=:id',[':id'=>$id])
            ->indexBy('fieldname')
            ->all();


        $fields = NewBusinessInspectionField::allField();

        foreach ($detail as $key => $value){
            if($value['fieldtype'] == 'image'){
                $ndetail['image'][] = Upload::checkGetUrl($value['val'],true);
            }else  if($value['fieldtype'] == 'textarea') {
                $ndetail['textarea'][] = $value;
            }else{
                $ndetail['input'][] = $value;
            }
        }

        $detail['situationinfo'] = $ndetail;

        return $this->render('@template/mobile/new_businessman_inspection_detail.html',[
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);
    }


    /**
     * @param $pigid
     * @return string
     * 出栏登记
     */
    public function actionPigOut($pigid)
    {
        //取出在宰杀方式
        $kill = SysSetting::getValue('killtype');
        foreach ($kill as $key => $row){
            $tdata = explode('@',$row);
            $data['title'] = $tdata[0];
            $data['price'] = $tdata[1];
            $data['desc'] = $tdata[2];
            $info[] =  $data;
        }

//        $info = [
//            ['title' => '土杀方式','desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。','price'=>200],
//            ['title' => '屠宰场宰杀','desc' => '通过突发宰杀的猪具有完整性，定制性等优点，可以依照用户需求，选择最佳的割肉方式，同时，猪肉的品质也会被保证到最好，具有独特的乡村风味。','price'=>300],
//        ];

        $outreason = SysSetting::getValue('outreason');
        return $this->render('@template/mobile/businessman_register_sale.html',[
            'pigid' => $pigid,
            'outreason' => $outreason,
            'info' => \GuzzleHttp\json_encode($info)
        ]);
    }


    /**
     * @return array
     * 提交出栏登记
     */
    public function actionPostPigOut()
    {
        $postdata = \Yii::$app->request->post();
        $ise = \Yii::$app->db->createCommand('select id from '.BusinessGrowup::tableName().' where pigid=:id')
            ->bindValues([':id'=>$postdata['pigid']])
            ->queryOne();
        if($ise){
            return $this->jsonMsg('该猪种已经预出栏',1);
        }
        if(!$postdata['pigid']){
            return $this->jsonMsg('参数错误',1);
        }

        $no = (new Query())->select('no')->from(BusinessPig::tableName())
            ->where('id=:id',[':id'=>$postdata['pigid']])
            ->scalar();

        $res = \Yii::$app->db->createCommand()->insert(BusinessGrowup::tableName() ,[
            'pigid' => $postdata['pigid'],
            'person' => $this->user['personid'],
            'reason' => $postdata['reason'],
            'descripation' => $postdata['descripation'],
            'createtime' => time(),
            'pigno' => $no,
//            'killtype' => $postdata['killtype'],
//            'killprice' => $postdata['killprice'],
        ])->execute();
        $growid = \Yii::$app->db->getLastInsertID();

        //更新仔猪状态
        $res = \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['status'=>BusinessPig::STATUS_WAITOUT],'id=:id',[':id'=>$postdata['pigid']])->execute();

        if($res){
            //模板消息通知
            $linger = (new Query())->select('no,u.openid')
                ->from(BusinessPig::tableName().' as p')
                ->leftJoin(BusinessUser::tableName().' as u','u.id=lingperson')
                ->where('p.id=:id',[':id'=>$postdata['pigid']])
                ->one();

            $data = [
                "first"  => "恭喜您领养编号为“".$linger['no']."”的仔猪已经出栏",
                "keyword1"   => "仔猪出栏",
                "keyword2"  => date('Y-m-d H:i:s'),
                "remark" => "欢迎再次光临！",
            ];
            $notice = \Yii::$app->wechat->notice->to($linger['openid'])
                ->url(\Yii::$app->request->hostInfo.'/business/user/sel-killtype?growid='.$growid)
                ->template(SysSetting::getValue('template_msgid'))
                ->andData($data)
                ->send();

            return $this->jsonMsg('登记成功',0);
        }else{
            return $this->jsonMsg('登记失败',1);
        }
    }


    /**
     * @return string
     * 异常处理
     */
    public function actionPigException($pigid)
    {

        //取出异常原因
        $exception = SysSetting::getValue('exception');
        $exception = array_merge($exception,[BusinessException::EXCEPTION_DIE]);
//        var_dump($exception);exit;
        return $this->render('@template/mobile/businessman_exception.html',[
            'pigid' => $pigid,
            'exceptionreason' => $exception,
        ]);

    }


    /**
     * @return array
     * 提交异常处理
     */
    public function actionPostPigException()
    {
        $postdata = \Yii::$app->request->post();

        $res = \Yii::$app->db->createCommand()->insert(BusinessException::tableName() ,[
            'pigid' => $postdata['pigid'],
            'person' => $this->user['personid'],
            'reason' => $postdata['reason'],
            'descripation' => $postdata['descripation'],
            'createtime' => time()
        ])->execute();

        //更新仔猪状态
        if($postdata['reason'] == BusinessException::EXCEPTION_DIE){        //死亡
            $res = \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['status'=>BusinessPig::STATUS_DIEED],'id=:id',[':id'=>$postdata['pigid']])->execute();
        }else{      //其他异常情况
            $res = \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['status'=>BusinessPig::STATUS_EXCEPTION],'id=:id',[':id'=>$postdata['pigid']])->execute();
        }
        if($res){
            return $this->jsonMsg('登记成功',0);
        }else{
            return $this->jsonMsg('登记失败',1);
        }

    }


    /**
     * @param $pigid
     * @return string
     * 价格跟踪
     */
    public function actionPriceTrack($pigid)
    {
        $price = BusinessPigPrice::find()
            ->select('id,type,weight,price')
            ->asArray()
            ->where('pigid=:pigid',[':pigid'=>$pigid])
            ->all();
        $pig = BusinessPig::find()->select('no,id')->asArray()->where('id=:id',[':id'=>$pigid])->one();

        $total_price = 0;
        $weight = 0;
        $detail['records'] = [];
        $detail['price'] = 0;
        if($price){
            foreach ($price as $key => $row){
                $total_price += $row['price'];
                $weight += $row['weight'];
                $row['no'] = str_pad($row['id'],5,0);
                $detail['records'][] = $row;
            }
            $detail['price'] = $total_price/$weight;
        }

        $detail['no'] =$pig['no'];
        $detail['weight'] = $weight;
        $detail['total_price'] = $total_price;

        return $this->render('@template/mobile/businessman_price_tracking.html',[
            'pigid' => $pigid,
            'detail' => \GuzzleHttp\json_encode($detail)
        ]);
    }


    /**
     * @return array
     * 价格跟踪
     */
    public function actionPostPriceTrack()
    {

        $postdata = \Yii::$app->request->post();
//        $postdata['pigid'] = 1;
        if(is_array($postdata['type']) && !empty($postdata['type'])){
            foreach ($postdata['type'] as $key => $row){
                $data['type'] = $row;
                $data['weight'] = $postdata['weight'][$key];
                $data['price'] = $postdata['price'][$key];
                $data['personid'] = $this->user['personid'];
                $data['pigid'] = $postdata['pigid'];
                $data['otherdesc'] = $postdata['pighouseinfo'];
                $data['createtime'] = time();
                $res = \Yii::$app->db->createCommand()->insert(BusinessPigPrice::tableName(),$data)->execute();
            }
            if($res){
                return $this->jsonMsg();
            }else{
                return $this->jsonMsg('操作失败',1);
            }
        }

        return $this->jsonMsg('请填写类型',1);



    }



    /**
     * @return string
     * 成本管理
     */
    public function actionCost($pigid)
    {
        $tyeps = BusinessCostType::find()->where('type=:type',[':type'=>BusinessCostType::TYPE_PIG])->asArray()->all();
        return $this->render('@template/mobile/businessman_cost_input.html',[
            'pigid' => $pigid,
            'types' => $tyeps
        ]);
    }


    /**
     * @return array
     * 添加成本管理
     */
    public function actionPostCost()
    {
        $postdata = \Yii::$app->request->post();
        if(empty($postdata['createtime'])){
            $postdata['createtime'] = time();
        }
        $type = BusinessCostType::findOne($postdata['typeid'])->name;
        $res = \Yii::$app->db->createCommand()->insert(BusinessCost::tableName() ,[
            'pigid' => $postdata['pigid'],
            'type' => $type,
            'typeid' => $postdata['typeid'],
            'personid' => $this->user['personid'],
            'person' => $this->user['personname'],
            'price' => $postdata['price'],
            'description' => $postdata['description'],
            'createtime' => $postdata['createtime'],
        ])->execute();

        if($res){
            return $this->jsonMsg('登记成功',0);
        }else{
            return $this->jsonMsg('登记失败',1);
        }
    }








    /**
     * @return string
     * 提醒说明
     */
    public function actionTipExplain()
    {

        $cates = ArticlesiteCategory::find()->asArray()->where(['usefor'=>ArticlesiteCategory::USEFOR_PERSON])->all();

        $query = ArticlesiteArticle::find()
            ->select('id,title,createtime as time')
            ->asArray();


        $cateid = \Yii::$app->request->get('cateid');
        if($cateid){
            $msgs = $query->where('usefor=:usefor and cateid=:cateid',[':usefor'=>ArticlesiteArticle::USEFOR_PERSON,'cateid'=>$cateid])
                ->all();
        }else{
            $msgs = $query->where('usefor=:usefor',[':usefor'=>ArticlesiteArticle::USEFOR_PERSON])
                ->all();
        }

        foreach($msgs as $key => $row)
        {
            $msgs[$key]['time'] = date('Y-m-d H:i:s',$row['time']);
            $msgs[$key]['url'] = \yii\helpers\Url::to(['person/tip-explain-detail','id'=>$row['id']]);
        }


        return $this->render('@template/mobile/businessman_message.html',[
            'msgs' => \GuzzleHttp\json_encode($msgs),
            'cates' => $cates
        ]);
    }


    /**
     * @param $id
     * @return string
     * 提醒说明详细
     */
    public function actionTipExplainDetail($id)
    {

        $detail = ArticlesiteArticle::find()
            ->select('id,title,content,createtime as time')
            ->asArray()
            ->where('id=:id',[':id'=>$id])
            ->one();
        return $this->render('@template/mobile/businessman_message_detail.html',[
            'detail' => $detail
        ]);
    }


    /**
     * @return string
     * 上报投放计划
     */
    public function actionDeliveryPlan()
    {
        //            var data = {records:[{no:"352651585",farmer:"张老三",num:"5"},{no:"352651585",farmer:"张老三",num:"5"},{no:"352651585",farmer:"张老三",num:"5"}]}

        $address = BusinessAdress::find()->select('id,parentid,lat,lng,name')->where('status=:status and type!=:type',[':status'=>BusinessAdress::STATUS_ACTIVE,':type'=>0])->asArray()->all();
        $address = Category::getTree($address,9);

        $farmer = BusinessFarmers::find()
            ->select('id,no,name as farmer,villageid')
            ->where('introducer=:personid and status=:status',[':personid'=>$this->user['personid'],':status'=>BusinessFarmers::STATUS_AGREE])
            ->asArray()
            ->all();

        $records = BusinessPutDetail::find()
            ->alias('pd')
            ->select('pd.id,pd.farmer as farmername,pd.num,a.name as address')
            ->leftJoin(BusinessPut::tableName().' as p','p.id=pd.putid')
            ->leftJoin(BusinessAdress::tableName().' as a','p.cunid=a.id')
            ->where('p.person=:person',[':person'=>$this->user['personid']])
            ->asArray()
            ->all();


        return $this->render('@template/mobile/businessman_farmers_report.html',[
            'farmer' => \GuzzleHttp\json_encode($farmer),
            'person' => $this->user,
            'address' => \GuzzleHttp\json_encode($address),
            'records' => \GuzzleHttp\json_encode($records)
        ]);
    }


    /**
     * 上报投放计划
     */
    public function actionPostDeliveryPlan()
    {
        $postdata = \Yii::$app->request->post();

        $farmers = ArrayHelper::getValue($postdata,'farmerid');
        if(count($farmers) != count(array_unique($farmers))){
            return $this->jsonMsg('农户不能一次性重复上报',1);
        }
        $totalnum = array_sum(ArrayHelper::getValue($postdata,'num'));

        //插入总体信息
        $data = [
            'person' => $this->user['personid'],
            'person_openid' => $this->user['openid'],
            'num' => $totalnum,
            'cunid' => $postdata['area'],
            'no' => date('ymdhms').rand(0,10000),
            'createtime' => time()
        ];

        $res = \Yii::$app->db->createCommand()->insert(BusinessPut::tableName(),$data)->execute();

        if($res){
            $putid = \Yii::$app->db->getLastInsertID();
            if(is_array($postdata['farmerid']) && !empty($postdata['farmerid'])){
                foreach($postdata['farmerid'] as $key => $row){
                    $data = [
                        'putid' => $putid,
                        'farmerid' => $postdata['farmerid'][$key],
                        'farmer' => $postdata['farmername'][$key],
                        'num' => $postdata['num'][$key],
                    ];
                    $res = \Yii::$app->db->createCommand()->insert(BusinessPutDetail::tableName(),$data)->execute();
                }
            }

            return $res?$this->jsonMsg():$this->jsonMsg('提交失败',1);
        }

        return $this->jsonMsg('提交失败',1);
    }


    /**
     * @return string
     * 防疫疫苗列表
     */
    public function actionVaccine($pigid)
    {

        //取出仔猪的批次
        $batch = (new Query())->select('batch')->from(BusinessPig::tableName())
            ->where('id=:id',[':id'=>$pigid])
            ->scalar();



        //取出应该打的疫苗
        $vaccine =  (new Query())->select(['vacset.vaccinename','vacset.date as shoulddate','vacset.id'])
            ->from(['vacset'=>BusinessVaccineSet::tableName()])
            ->where('batch=:batch',[':batch'=>$batch])
            ->all();

        //取出疫苗记录
        foreach ($vaccine as $key => $row){
            $vaccine[$key]['recorddate'] =  \Yii::$app->db->createCommand('select date from '.BusinessVaccine::tableName().' where pigid=:pigid and vaccineid=:vacesetid')
                ->bindValues([':vacesetid'=>$row['id'],':pigid'=>$pigid])
                ->queryScalar();
        }

        return $this->render('@template/mobile/businessman_vaccine.html',[
            'vaccine' => $vaccine,
            'pigid' => $pigid
        ]);
    }

    /**
     * @return string
     * 添加疫苗
     */
    public function actionVaccineForm($pigid,$vacsetid)
    {

        //取出仔猪的批次
        $batch = (new Query())->select('batch')->from(BusinessPig::tableName())
            ->where('id=:id',[':id'=>$pigid])
            ->scalar();

        //取出要打的疫苗
        $vaccine = (new Query())->select(['vacset.vaccinename','vacset.date as shoulddate','vacset.id'])
            ->from(['vacset'=>BusinessVaccineSet::tableName()])
            ->where('id=:id',[':id'=>$vacsetid])
            ->one();


        //取出疫苗记录
        $varecords = (new Query())
            ->select('vac.id,vac.vaccinename,vac.createtime,vac.date,vset.date as shoulddate')->from(BusinessVaccine::tableName().' as vac')
            ->leftJoin(['vset'=>BusinessVaccineSet::tableName()],'vset.id=vac.vaccineid')
            ->where('pigid=:pigid',[':pigid'=>$pigid])
            ->all();

        return $this->render('@template/mobile/businessman_vaccine_form.html',[
            'vaccine' => $vaccine,
            'varecords' => $varecords
        ]);
    }


    /**
     * @return array
     * 搜索仔猪
     */
    public function actionSearchPig()
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;

        $kwd = \Yii::$app->request->post('keywords');

        $pigs = (new Query())->from(BusinessPig::tableName().' as p')
            ->select('p.id,p.status,p.no,p.headperson as owner,p.liveryname as farmer,p.photo as img,v.title as type')
            ->leftJoin(BusinessVariety::tableName().' as v','p.varietyid=v.id')
            ->where('p.headpersonid=:id and livery!=0 and `no` like :kwd',[':id'=>$this->user['personid'],':kwd'=>"%$kwd%"])
            ->all();

        foreach ($pigs as $key => $value){
            $pigs[$key]['img'] = Upload::checkGetUrl($value['img']);
            $pigs[$key]['oldstatus'] = $value['status'];
            $pigs[$key]['status'] = BusinessPig::$statues[$value['status']];
            $pigs[$key]['url'] = \yii\helpers\Url::to(['person/pig-detail','pigid'=>$value['id']]);
        }

        return $pigs?$pigs:$this->jsonMsg('没有对应的仔猪',1);

    }

    /**
     * @param $pigid
     * 疾病处理
     */
    public function actionDisease($pigid)
    {
        $types = BusinessDiseaseType::find()->select('*')->where(['status'=>BusinessDiseaseType::STATUS_SHOW])->asArray()->all();

        $disea = (new Query())->select('step,id')->from(BusinessDisease::tableName())->orderBy('id desc')->one();
        $diseaid = 0;
        $diseastep = 0;
        if($disea != false && $disea['step'] != BusinessDisease::RECOVERED){
            $diseaid = $disea['id'];
            $diseastep = $disea['step'];
        }
        return $this->render('@template/mobile/businessman_disease.html',[
            'types' => $types,
            'pigid' => $pigid,
            'step' => BusinessDisease::$steps,
            'diseaid' => $diseaid,
            'diseastep' => $diseastep,
        ]);
    }


    /**
     * @return array
     * 提交疾病
     */
    public function actionPostDisease()
    {
        $postdata = \Yii::$app->request->post();

        $data = [
            'pigid' => $postdata['pigid'],
            'personid' => $this->user['personid'],
            'person' => $this->user['personname'],
            'type' => $postdata['type'],
            'detail' => $postdata['detail'],
            'createtime' => time(),
            'step' => $postdata['step'],
        ];
        $step = (new Query())->select('step')->from(BusinessDisease::tableName())->where('id=:id',[':id'=>$postdata['diseaid']])->orderBy('id desc')->scalar();
        //有疾病未治愈,更新治疗进度
        if($step!=BusinessDisease::RECOVERED && $step!==false){
            $res = \Yii::$app->db->createCommand()->update(BusinessDisease::tableName(),$data,['id'=>$postdata['diseaid']])->execute();
        }else{
            $res = \Yii::$app->db->createCommand()->insert(BusinessDisease::tableName(),$data)->execute();
        }
        return $res?$this->jsonMsg():$this->jsonMsg('失败',1);

    }


    /**
     *上传仔猪视频
     */
    public function actionUpvideo($pigid)
    {
        $this->enableCsrfValidation = false;

        if(\Yii::$app->request->isPost){
            $res = Upload::uploadByName('file','video',false);
            if($res){
                //入库
                \Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['video'=>$res],'id=:id',['id'=>$pigid])->execute();
                \Yii::$app->db->createCommand()->insert('business_pig_videos_history',['pigid'=>$pigid,'video'=>$res])->execute();
                return '0';
            }
            return '1';
        }

        return $this->render('@template/mobile/businessman_upvideo');

    }












}
